All files / src/app/api/admin/affiliates/[id] route.ts

0% Statements 0/194
100% Branches 0/0
0% Functions 0/1
0% Lines 0/194

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195                                                                                                                                                                                                                                                                                                                                                                                                     
export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from 'next/server';
import { Session } from "next-auth";
import { prisma } from "@/lib/prisma";
import { z } from "zod";
import { affiliateSystem } from "@/lib/affiliate-system";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";

interface RouteParams {
  params: Promise<{ id: string }>;
}

/**
 * GET /api/admin/affiliates/[id]
 * Get a single affiliate with detailed stats
 */
async function handleGet(
  _request: NextRequest,
  context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const affiliateId = parseInt(id);

  if (isNaN(affiliateId)) {
    throw ApiError.badRequest("Invalid affiliate ID");
  }

  const affiliate = await prisma.affiliate.findUnique({
    where: { id: affiliateId },
    include: {
      clicks: {
        orderBy: { clickedAt: "desc" },
        take: 20},
      sales: {
        orderBy: { createdAt: "desc" },
        take: 20},
      payouts: {
        orderBy: { requestedAt: "desc" },
        take: 10}}});

  if (!affiliate) {
    throw ApiError.notFound("Affiliate");
  }

  // Get user info
  const user = await prisma.user.findUnique({
    where: { id: affiliate.userId },
    select: { id: true, name: true, email: true }});

  // Get fraud detection results
  const fraudCheck = await affiliateSystem.detectFraud(affiliateId);

  return successResponse({
    ...affiliate,
    user,
    fraudCheck});
}

// Schema for updating an affiliate
const updateAffiliateSchema = z.object({
  commissionType: z.enum(["PERCENTAGE", "FIXED_AMOUNT", "TIERED"]).optional(),
  commissionRate: z.number().min(0).max(100).optional(),
  tier: z.enum(["BRONZE", "SILVER", "GOLD", "PLATINUM"]).optional(),
  status: z
    .enum(["PENDING", "ACTIVE", "SUSPENDED", "REJECTED", "INACTIVE"])
    .optional(),
  payoutMethod: z.string().max(50).optional().nullable(),
  minimumPayout: z.number().min(0).optional(),
  website: z.string().max(255).optional().nullable(),
  bio: z.string().optional().nullable()});

/**
 * PUT /api/admin/affiliates/[id]
 * Update an affiliate
 */
async function handlePut(
  request: NextRequest,
  context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const affiliateId = parseInt(id);

  if (isNaN(affiliateId)) {
    throw ApiError.badRequest("Invalid affiliate ID");
  }

  const body = await request.json();
  const result = updateAffiliateSchema.safeParse(body);

  if (!result.success) {
    throw ApiError.validation("Invalid affiliate data", result.error.issues);
  }

  const validatedData = result.data;

  // Check if affiliate exists
  const existing = await prisma.affiliate.findUnique({
    where: { id: affiliateId }});

  if (!existing) {
    throw ApiError.notFound("Affiliate");
  }

  // Build update data
  const updateData: Record<string, unknown> = {};

  if (validatedData.commissionType !== undefined) {
    updateData.commissionType = validatedData.commissionType;
  }
  if (validatedData.commissionRate !== undefined) {
    updateData.commissionRate = validatedData.commissionRate;
  }
  if (validatedData.tier !== undefined) {
    updateData.tier = validatedData.tier;
  }
  if (validatedData.status !== undefined) {
    updateData.status = validatedData.status;
    // Set approval date if activating
    if (validatedData.status === "ACTIVE" && existing.status !== "ACTIVE") {
      updateData.approvedAt = new Date();
      updateData.approvedBy = session.user.id;
    }
  }
  if (validatedData.payoutMethod !== undefined) {
    updateData.payoutMethod = validatedData.payoutMethod;
  }
  if (validatedData.minimumPayout !== undefined) {
    updateData.minimumPayout = validatedData.minimumPayout;
  }
  if (validatedData.website !== undefined) {
    updateData.website = validatedData.website;
  }
  if (validatedData.bio !== undefined) {
    updateData.bio = validatedData.bio;
  }

  const affiliate = await prisma.affiliate.update({
    where: { id: affiliateId },
    data: updateData});

  return successResponse(affiliate);
}

/**
 * DELETE /api/admin/affiliates/[id]
 * Delete an affiliate (soft delete by setting status to INACTIVE)
 */
async function handleDelete(
  _request: NextRequest,
  context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const affiliateId = parseInt(id);

  if (isNaN(affiliateId)) {
    throw ApiError.badRequest("Invalid affiliate ID");
  }

  // Check if affiliate exists
  const existing = await prisma.affiliate.findUnique({
    where: { id: affiliateId }});

  if (!existing) {
    throw ApiError.notFound("Affiliate");
  }

  // Check for pending payouts
  const pendingPayouts = await prisma.affiliatePayout.count({
    where: { affiliateId, status: { in: ["PENDING", "PROCESSING"] } }});

  if (pendingPayouts > 0) {
    throw ApiError.badRequest("Cannot delete affiliate with pending payouts");
  }

  // Soft delete by setting status to INACTIVE
  await prisma.affiliate.update({
    where: { id: affiliateId },
    data: { status: "INACTIVE" }});

  return successResponse({ message: "Affiliate deactivated successfully" });
}

export const GET = withErrorHandling(withAdmin(handleGet));
export const PUT = withErrorHandling(withAdmin(handlePut));
export const DELETE = withErrorHandling(withAdmin(handleDelete));